<?php

/**
 * Users Online class
 *
 * Manages active users
 *
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Add-Ons
 * @author Leonardo Monteiro Bersan de Araújo
 * @link hhttp://codeigniter.com/wiki/Library: Online_Users
 */
class Users_Online {

    var $file = "usersonline.tmp";
    var $data;
    var $ip;
    
    function __construct() {
        register_shutdown_function('_disconect');;
    }

    function start() {
        $this->ip = $_SERVER['REMOTE_ADDR'];
        $this->data = @unserialize(file_get_contents($this->file));
        if (!$this->data)
            $this->data = array();

        $timeout = time() - 120;

//If it's the first hit, add the information to database
        if (!isset($this->data[$this->ip])) {
            $this->data[$this->ip]['time'] = time();
            $this->data[$this->ip]['uri'] = $_SERVER['REQUEST_URI'];
            $CI = & get_instance();
//Loads the USER_AGENT class if it's not loaded yet
            if (!isset($CI->agent)) {
                $CI->load->library('user_agent');
                $class_loaded = true;
            }
            if ($CI->agent->is_robot())
                $this->data[$this->ip]['bot'] = $CI->agent->robot();
            else
                $this->data[$this->ip]['bot'] = false;

//Destroys the USER_AGENT class so it can be loaded again on the controller
            if ($class_loaded)
                unset($class_loaded, $CI->agent);
        }
        else {
            $this->data[$this->ip]['time'] = time();
            $this->data[$this->ip]['uri'] = $_SERVER['REQUEST_URI'];
        }

//Removes expired data
        foreach ($this->data as $key => $value) {
            if ($value['time'] <= $timeout)
                unset($this->data[$key]);
        }

        $this->_save();
        
    }
    
    

//this function return the total number of online users
    function total_users() {
        $this->data = @unserialize(file_get_contents($this->file));
        return count($this->data); //this return not work
    }
    
    function _save(){
     file_put_contents($this->file, serialize($this->data));
    }
    
    
    function disconect(){
        
        file_put_contents('dis.txt', 'discont'.date('d/m/Y H:i:s'));
    }

}
